using System;
using System.Collections.Generic;
using System.Text;
using Task.Contracts;
using DataAccess;

namespace Task
{
    public class TagTask : ITagTask
    {
        private tag AddTag(string tag)
        {
            NHibernateDao<tag, int> factory = new NHibernateDao<tag, int>();
            tag newTag = new tag();
            newTag.name = tag;
            factory.Save(newTag);
            return newTag;
        }

        private tag readTagByTagName(string tagName)
        {
            NHibernateDao<tag, int> factory = new NHibernateDao<tag, int>();
            List<tag> list = factory.GetByCriteria(NHibernate.Expression.Expression.Eq("name", tagName));

            if ((list == null) || (list.Count == 0))
                return null;

            foreach (tag t in list)
            {
                return t;
            }
            return null;
        }

        public void AddTagsToArt(int artId, List<string> tags)
        {
            if( (tags==null) || (tags.Count == 0))
                return;

            NHibernateDao<art, int> artFactory = new NHibernateDao<art, int>();
            art artTmp = artFactory.GetById(artId,false);

            foreach (string tagTmpString in tags)
            {
                NHibernateDao<art_tag, int> art_tagFactory = new NHibernateDao<art_tag, int>();
                art_tag art_tagTmp = new art_tag();

                tag tagTmp = readTagByTagName(tagTmpString);
                if (tagTmp == null)
                    tagTmp = AddTag(tagTmpString);
                art_tagTmp.art = artTmp;
                art_tagTmp.tag = tagTmp;
                art_tagFactory.Save(art_tagTmp);
            }
        }

        public List<tag> ReadAllTags()
        {
            NHibernateDao<tag, int> tagFactory = new NHibernateDao<tag, int>();
            return tagFactory.GetAll();
        }

        public List<tag> ReadTagsByArtId(int artId)
        {
            NHibernateDao<art_tag, int> factory = new NHibernateDao<art_tag, int>();
            List<art_tag> list 
                = factory.GetByCriteria(NHibernate.Expression.Expression.Eq("art_id", artId));
            List<tag> tags = new List<tag>();
            foreach (art_tag artTag in list)
            {
                tags.Add(artTag.tag);
            }
            return tags;
        }
    }
}
